"""
通过字符串来操作对象的属性或方法
"""


class User:
    school = "oldgirl"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def func(self):
        print("func")


# hasattr判断user类是否有某个属性和方法
print(User.school)
print('school' in User.__dict__)
print('func' in User.__dict__)
print(hasattr(User, 'school'))
print(hasattr(User, 'func'))
# getattr获取对象属性
print(getattr(User, 'school'))
print(getattr(User, 'func', 'default'))  # 如果没有这个属性就返回默认值
print(User.__dict__['school'])
d = {'name': '高嘉银'}
print(d.get('name', 'default'))  # 字典的get方法获取属性，如果没有这个值就返回默认值

# setattr
obj = User('廖立晴', '20')
setattr(obj, 'gender', 'male')
print(obj.__dict__)
# delattr
delattr(User, 'school')


# 反射应用示例
class Ftp:
    def get(self):
        print('get')

    def put(self):
        print('put')

    def post(self):
        print('post')

    def run(self):
        while True:
            cmd = input('please input your cmd>>>:').strip()
            if hasattr(self, cmd):
                method = getattr(self, cmd)
                method()
            else:
                print("当前命令不存在")


obj = Ftp()
obj.run()
